<?php
/*
 * Author: top-songshijie
 * Email :997031758@qq.com
 * DateTime: 2023/06/09 15:49
 */

namespace SSJ\LaravelHelper\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response as IlluminateResponse;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

class MakeRequestTraceIdMiddleware
{
    /**
     * 总处理
     *
     * @param Request $request
     * @param Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request_trace_id = $request->header('Request-Trace-Id');
        if (!$request_trace_id) {
            $request_trace_id = (string)md5(uniqid() . time());
            $request->headers->set('Request-Trace-Id', $request_trace_id);
        }

        $response = $next($request);
        if ($response instanceof SymfonyResponse) {
            $response->headers->set('Request-Trace-Id', $request_trace_id);
        } elseif ($response instanceof IlluminateResponse) {
            $response->header('Request-Trace-Id', $request_trace_id);
        }
        return $response;
    }
}
